package com.kfm.base.net;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.JsonObject;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.*;
import java.util.Arrays;
import java.util.Base64;

public class UDPDemo {

    public static void main(String[] args) {
        try (DatagramSocket client = new DatagramSocket();
             FileInputStream fis = new FileInputStream("C:\\Users\\10854\\Pictures\\zl.webp");) {

            int port = 8888;
            InetAddress inetAddress = InetAddress.getLocalHost();

            byte[] bytes = new byte[1024 * 30];
            int length;
            while ( (length = fis.read(bytes)) != -1) {
                JsonObject jsonObject = new JsonObject();
                jsonObject.addProperty("end", false);
                jsonObject.addProperty("data", Base64.getEncoder().encodeToString(Arrays.copyOf(bytes, length)));
                String string = jsonObject.toString();
                DatagramPacket packet = new DatagramPacket(string.getBytes(), string.getBytes().length, inetAddress, port);
                client.send(packet);
            }
            // 告诉服务端发送结束
            JsonObject jsonObject = new JsonObject();
            jsonObject.addProperty("end", true);
            jsonObject.addProperty("data", "");
            String string = jsonObject.toString();
            DatagramPacket packet = new DatagramPacket(string.getBytes(), string.getBytes().length, inetAddress, port);
            client.send(packet);

            System.out.println("发送成功");
        } catch (SocketException e) {
            throw new RuntimeException(e);
        } catch (UnknownHostException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }
}

class UDPDemo02 {

    public static void main(String[] args) {
        try (DatagramSocket server = new DatagramSocket(8888);
             FileOutputStream fos = new FileOutputStream("d://zl.webp", true);
        ) {


            while (true) {
                byte[] bytes = new byte[1024 * 1024 * 100];
                DatagramPacket packet = new DatagramPacket(bytes, bytes.length);
                server.receive(packet);
                byte[] data = packet.getData();
                String s = new String(data, 0, packet.getLength());
                JSONObject jsonObject = JSONObject.parseObject(s);
                if (jsonObject.getBoolean("end")){
                    break;
                }
                String string = jsonObject.getString("data");
                byte[] bytes1 = Base64.getDecoder().decode(string);
                fos.write(bytes1);
            }


        } catch (SocketException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
